package com.yl.users.services.impl

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper
import com.baomidou.mybatisplus.core.toolkit.Wrappers
import com.yl.common.ErrorCode
import com.yl.common.control.ResponseBody
import com.yl.common.control.returnError
import com.yl.common.control.returnSuccess
import com.yl.users.common.enum.TodoFlag
import com.yl.users.entity.CompanyUserTodo
import com.yl.users.mapper.CompanyUserTodoMapper
import com.yl.users.services.ICompanyUserTodoService
import org.springframework.stereotype.Service
import java.util.*

@Service
class CompanyUserTodoServiceImpl(
        private val companyUserTodoMapper: CompanyUserTodoMapper
) : ICompanyUserTodoService {

    override fun detail(id: Long): CompanyUserTodo {
        return companyUserTodoMapper.selectById(id)
    }

    override fun edit(companyUserTodo: CompanyUserTodo): ResponseBody {
        if (companyUserTodo.id == null || companyUserTodo.id == 0L) {
            return returnError(ErrorCode.DATA_IS_NOT_FIND)
        }
        companyUserTodoMapper.selectById(companyUserTodo.id) ?: return returnError(ErrorCode.DATA_IS_NOT_FIND)

        if (companyUserTodo.title.isEmpty()) {
            return returnError(ErrorCode.PARAM_EMPTY, "请填写标题")
        }
        if (companyUserTodo.content.isEmpty()) {
            return returnError(ErrorCode.PARAM_EMPTY, "请填写内容")
        }
        if (companyUserTodo.planTime == null) {
            return returnError(ErrorCode.PARAM_EMPTY, "请输入计划时间")
        }
        companyUserTodoMapper.updateById(companyUserTodo)
        return returnSuccess()
    }

    override fun del(id: Long): ResponseBody {
        companyUserTodoMapper.deleteById(id)
        return returnSuccess()
    }

    override fun updateAllToTimeOut(): ResponseBody {
        val updateWrapper =
                UpdateWrapper<CompanyUserTodo>().set("flag", TodoFlag.TIME_OUT.code)
                        .le("flag", TodoFlag.COMPLETED.code - 1)
                        .ge("plan_time", Date())
        companyUserTodoMapper.update(null, updateWrapper)
        return returnSuccess()
    }

    override fun updateToComplete(id: Long): ResponseBody {
        companyUserTodoMapper.update(null,Wrappers.update<CompanyUserTodo?>().eq("id",id)
            .set("flag",TodoFlag.COMPLETED.code)
            .set("real_time",Date()))
        return returnSuccess()
    }

    override fun setFlag(id: Long, flag: TodoFlag): ResponseBody {
        companyUserTodoMapper.update(null,Wrappers.update<CompanyUserTodo?>().eq("id",id)
            .set("flag",flag.code))
        return returnSuccess()
    }
}
